import { getCurrentInstance, reactive, ref } from 'vue';
import { processToFile } from '@/api/parser.js';
import { useRouter } from 'vue-router';
import { getIsAdmin } from '@/utils/cookie.js';

export function useUploadFile() {
  const instance = getCurrentInstance();
  const { $message } = instance.appContext.config.globalProperties;
  const router = useRouter();

  const activeStep = ref(0);
  const activeLine = ref(-1);
  // 用来判断上传是否成功 和 文件是否删除
  const uploadSuccess = ref(false);
  const fileName = ref(''); // 上传文件的文件名称
  const uploadLoading = ref(false); // 格式上传按钮loading
  let uploadFile = {}; // 上传的文件
  /**
   * @desc 上传文件
   */
  // 文档上传函数
  async function wordUpload(file) {
    uploadFile = file;
    uploadSuccess.value = true;
    fileName.value = file.file.name;
    activeLine.value = 0;
  }
  // 清理文档
  function cleanWord() {
    uploadSuccess.value = false;
    activeLine.value = -1;
    uploadFile = {};
  }
  // 预览
  const showPreviewDialog = ref(false); // 预览弹窗
  // 预览数据
  let previewData = reactive({});
  function previewClick(item) {
    Object.assign(previewData, item);
    showPreviewDialog.value = true;
  }
  // 格式生成
  async function formatHandle(item) {
    const formData = new FormData();
    formData.append('file', uploadFile.file, fileName.value);
    formData.append('tplCode', item.tplCode);
    formData.append('tplId', item.tplId);
    formData.append('qkLwId', item.qkLwId);
    formData.append('qkLwName', item.qkLwName);
    if (uploadLoading.value) {
      $message.info('正在生成格式，请稍后！');
      return false;
    }
    const loadingMessage = $message({
      message: '格式生成中!',
      type: 'info',
      duration: 0,
    });
    const returnData = await processToFile(formData);
    uploadLoading.value = true;
    if (returnData?.code === 200) {
      activeStep.value = 2;
      activeLine.value = 1;
      loadingMessage.close();
      uploadLoading.value = false;
    } else {
      loadingMessage.close();
      $message.error(returnData?.msg);
      uploadLoading.value = false;
      return false;
    }
    activeStep.value = 2;
    activeLine.value = 1;
  }
  // 立即查看
  function lookHandle() {
    router.push({ path: '/personalCenter', query: { moduleName: 'record' } }).then();
  }
  // 上传模板跳转函数
  function uploadJumpHandle() {
    const isAdmin = getIsAdmin();
    const moduleName = isAdmin === 'true' ? 'systemModule' : 'addModule';
    router.push({ path: '/personalCenter', query: { moduleName } }).then();
  }
  // 返回上一步
  function goLastStep() {
    activeStep.value = 0;
    activeLine.value = -1;
  }

  return {
    activeStep,
    activeLine,
    uploadSuccess,
    uploadLoading,
    fileName,
    wordUpload,
    cleanWord,
    showPreviewDialog,
    previewData,
    previewClick,
    formatHandle,
    lookHandle,
    uploadJumpHandle,
    goLastStep,
  };
}
